package com.vodafone.mapreduce.inputreader;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

import org.apache.log4j.Logger;

public class WordCountInputReader implements InputReader<String, String> {

	public static Logger log = Logger.getLogger(WordCountInputReader.class);

	@Override
	public String read(String fileName) {
		URL fileUrl = this.getClass().getResource(fileName);
		if (fileUrl == null) {
			log.error("file \"" + fileName + "\" not found");
			return null;
		}
		log.debug("fileUrl: " + fileUrl);
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(fileUrl.getFile()));
			char[] chunk = new char[1024];
			int charsRead = 0;
			while ((charsRead = br.read(chunk, 0, chunk.length)) != -1) {
				sb.append(chunk, sb.length(), charsRead);
			}
		} catch (FileNotFoundException fnfe) {
			log.error(fnfe);
		} catch (IOException ioe) {
			log.error(ioe);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException ignored) { }
			}
		}
		return sb.toString();
	}
}
